/*
 * @Description: 路由后置钩子
 * @Author: HuiSir<273250950@qq.com>
 * @Date: 2021-09-20 18:59:01
 * @LastEditTime: 2025-08-15 10:09:18
 */
import { project } from "@/init/config";
import { NavigationHookAfter } from "vue-router";
import PageLoading from "@/utils/PageLoading";
import { useAdminStore, useLayoutStore } from "@/store";

const useAfterEach: NavigationHookAfter = (to, from, failure) => {
  // store
  const adminStore = useAdminStore();

  // 导航出错终止
  if (failure) {
    // 关闭loading
    PageLoading.hide();
    if (
      adminStore.isLogin &&
      !failure.toString().includes("Avoided redundant")
    ) {
      console.warn(failure);
    }
    return;
  }

  const layoutStore = useLayoutStore();

  // 框架标题获取
  if (to.name === "Frame") {
    to.meta.title = (
      adminStore.menus.find((item) => item.id === to.params.id) as Permission
    ).title;
  }

  // 使用router.push()方法时可以通过query动态设置title
  // 动态设置的title替换原title
  if (to.query.title) {
    to.meta.title = to.query.title;
  }

  // 更改网页标题，这里在改变路由使用router.push()方法时可以通过query动态设置title
  if (to.meta.title) {
    document.title = to.meta.title + " - " + project.siteTitle;
  }

  // 关闭loading
  PageLoading.hide();

  // 更新历史记录
  layoutStore.addHistoryRoute(to);
};

export default useAfterEach;
